package cn.flying.cloud.flow.view.context;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import cn.flying.cloud.flow.annotation.FormController;
import cn.flying.cloud.flow.view.ForwardViewStrategy;

/**
 * @author: admin
 * @date: 2025年06月24日 16:44
 * @version: 1.0
 */
@Component
public class ForwardViewStrategyContext implements ApplicationContextAware, DisposableBean {

    protected Map<String, ForwardViewStrategy> beanCache = new ConcurrentHashMap<>();

    public ForwardViewStrategy getBean(String name) {
        return beanCache.get(name);
    }

    /**
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, ForwardViewStrategy> beans = applicationContext.getBeansOfType(ForwardViewStrategy.class);
        beans.forEach((name, bean) -> {
            Class<? extends ForwardViewStrategy> clazz = bean.getClass();
            if (clazz.isAnnotationPresent(FormController.class)) {
                beanCache.put(name, bean);
            }
        });
    }


    /**
     * @throws Exception
     */
    @Override
    public void destroy() throws Exception {
        beanCache.clear();
    }
}
